package com.xsq.util;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.codehaus.xfire.util.Base64;

import com.alibaba.fastjson.JSON;
import com.xsq.Constant;

public class HttpInterface {
	
	private ServerUtils serverUtils;
	
	public static String urlPrex = "http://${SERVER}/EduOpenPlatform/api?";
	
	public HttpInterface(){
	}
	
	public HttpInterface(ServerUtils serverUtils){
		this.serverUtils = serverUtils;
	}

	
	
	
	public static void main(String[] args) {
		HttpInterface hi = new HttpInterface();
		String requestConent = null;
		String result = null;
		
		//{"balance":2300,"cardno":"1190021094","cardsno":"5F80108D","cardstatus":0,"return_code":"1","return_msg":"查询成功","username":"李雪艳"}
		boolean encrypt = false;
//		requestConent = RequestUtil.generateSrchCardInfoRequest(encrypt, "5F80108D", "1190021094");
//		result = Util.getResult(urlPrex.replace("${SERVER}", "test.szzhjy.net"),requestConent);
//		System.out.println(result);
		
//		long time1 = System.currentTimeMillis();
//		requestConent = RequestUtil.generateOnlineConsumeRequest(encrypt, "abcd", "44408", "AB7F118D", "1690019745", "20", "20171214133401", "21218CCA77804D2BA1922C33E0151105");
//		result = Util.getResult(urlPrex.replace("${SERVER}", "test.szzhjy.net"),requestConent);
//		System.out.println(result);
//		long time2 = System.currentTimeMillis();
//		System.out.println("请求到返回，耗时--》 "+(time2-time1)+" 毫秒");
//		
//		System.out.println("-----------mac验证-----------");
//		
//		Map<String,Object> rsMap = JSON.parseObject(result, Map.class);
//		String mac = String.valueOf(rsMap.get("mac"));
//		String flowcode = String.valueOf(rsMap.get("flowcode"));
//		String consumetime = String.valueOf(rsMap.get("consumetime"));
//		SignUtils signUtils = new SignUtilsImpl();
//		boolean validRs = signUtils.verify(flowcode+consumetime, mac, Constant.publicKey, Constant.SIGNATURE_ALGORITHM);
//		System.out.println("验证结果:"+validRs);
		
		
		
		requestConent = RequestUtil.generatePosAuthRequest(encrypt, "867377021144112", "44408", "616");
		result = Util.getResult(urlPrex.replace("${SERVER}", "test.szzhjy.net"),requestConent);
		System.out.println(result);
	}
	
	
	public String getLatestVersion() {

		try{
			
			String result  = null;
			List<String> serverList = serverUtils.getAllAviableServers();
			if (serverList == null || serverList.isEmpty()) {
				// 尝试依次服务器查询
				serverList = serverUtils.getAllServers();
				for (String name : serverList) {
					result = Util.getResult("http://${SERVER}/EduOpenPlatform/posApp/getAppVersion.do".replace("${SERVER}", name), "");
					if (result != null) {
						serverUtils.setServer(name, "1");
						break;
					}
				}
			} else {
				for (String server : serverList) {
					result = Util.getResult("http://${SERVER}/EduOpenPlatform/posApp/getAppVersion.do".replace("${SERVER}", server), "");
					if (result != null) {
						serverUtils.setServer(server, "1");
						break;
					} else {
						serverUtils.setServer(server, "0");
					}
				}
			}

			if (result == null) {
				
				return "0";
			} else {
				Map<String,Object> rsInfo = JSON.parseObject(result, Map.class);
				if(String.valueOf(rsInfo.get("is_success")).equals("1")){
					return String.valueOf(rsInfo.get("version"));
				}else{
					return "0";
				}
			}
		}catch(Exception e){
			return "0";
		}
		
		

	}
	
	
	/**
	 * 验证上位机是否正常可用
	 * @param server
	 * @param posno
	 * @param winno
	 * @return
	 */
	public Map<String, Object> testServer(String server, String posno, String winno) {
		boolean encrypt = false;
		String result = Util.getResult(urlPrex.replace("${SERVER}", server), RequestUtil.generateServerTestRequest(encrypt, posno, winno));
		Map<String, Object> rsInfo = new HashMap<String, Object>();
		rsInfo.put("is_success", -100);
		if (result == null) {
			//没连上
			return rsInfo;
		}
		String rs = null;
		if (encrypt) {
			try {
				rs = new String(Base64.decode(result), "UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				return rsInfo;
			}
		} else {
			rs = result;
		}
		Map<String, Object> jsonRs = JSON.parseObject(rs, Map.class);
		if (jsonRs.get("return_code") != null && String.valueOf(jsonRs.get("return_code")).equalsIgnoreCase("1")) {
			jsonRs.put("is_success", 1);
		} else {
			jsonRs.put("is_success", 0);
		}
		return jsonRs;
	}

	/**
	 * 根据卡号查询用户信息
	 * 
	 * @param params
	 * @return
	 */
	public Map<String, Object> getUserInfo(String cardsno,String cardno) {
		
		boolean encrypt = false;
		String requestConent = RequestUtil.generateSrchCardInfoRequest(encrypt, cardsno, cardno);
		Map<String,Object> jsonRs = doCommonRequest(encrypt, requestConent);
		return jsonRs;
	}

	/**
	 * 消费请求
	 * 
	 * @param params
	 * @return
	 */
	public Map<String, Object> doConsume(String flowid, String posno,String cardsno, String cardno,
			String amount, String consumetime, String consumepwd) {
		boolean encrypt = false;
		String requestConent = RequestUtil.generateOnlineConsumeRequest(encrypt, flowid, posno, cardsno, cardno, amount, consumetime, consumepwd);
		Map<String, Object> jsonRs = doCommonRequest(encrypt, requestConent);
		return jsonRs;
	}

	/**
	 * 通讯参数验证
	 * @param posno
	 * @param possno
	 * @param winno
	 * @return
	 */
	public Map<String, Object> validatePosParam(String posno, String possno, String winno) {

		boolean encrypt = false;
		String requestConent = RequestUtil.generatePosAuthRequest(encrypt, possno, posno, winno);
		Map<String,Object> jsonRs = doCommonRequest(encrypt, requestConent);
		return jsonRs;
	}
	
	/**
	 * 刷新链路
	 * @param posno
	 * @param curTime
	 * @return
	 */
	public Map<String, Object> refreshPosLink(String posno,String curTime,Map<String,Object> otherInfo) {

		boolean encrypt = false;
		String requestConent = RequestUtil.generatePosLinkRequest(encrypt,posno,curTime,otherInfo);
		Map<String,Object> jsonRs = doCommonRequest(encrypt, requestConent);
		return jsonRs;
	}
	

	
	/**
	 * 机器流水查询
	 * @param posno
	 * @param possno
	 * @param winno
	 * @return
	 */
	public Map<String, Object> srchPosFlow(String posno, String winno,String beginTime,String endTime,String page,String consumeType) {

		boolean encrypt = false;
		String requestConent = RequestUtil.generatePosFlowSrchRequest(encrypt, posno, winno,beginTime,endTime,page,consumeType);
		Map<String,Object> jsonRs = doCommonRequest(encrypt, requestConent);
		return jsonRs;
	}
	
	/**
	 * 机器收入统计
	 * @param posno
	 * @param possno
	 * @param winno
	 * @return
	 */
	public Map<String, Object> srchFlowStat(String posno, String winno,String beginTime,String endTime) {

		boolean encrypt = false;
		String requestConent = RequestUtil.generatePosFlowStatRequest(encrypt, posno, winno,beginTime,endTime);
		Map<String,Object> jsonRs = doCommonRequest(encrypt, requestConent);
		return jsonRs;
	}

	public Map<String, Object> srchJcRecord(String posno, String winno,String beginTime,String endTime,String page) {

		boolean encrypt = false;
		String requestConent = RequestUtil.generateSrchJcLogRequest(encrypt, posno, winno,beginTime,endTime,page);
		Map<String,Object> jsonRs = doCommonRequest(encrypt, requestConent);
		return jsonRs;
	}

	
	/**
	 * 查询最近的一笔交易
	 * @param posno
	 * @param winno
	 * @param beginTime
	 * @param endTime
	 * @param page
	 * @return
	 */
	public Map<String, Object> doSrchLateConsumeFlow(String posno, String winno) {

		boolean encrypt = false;
		String requestConent = RequestUtil.generateSrchLateFlowRequest(encrypt, posno, winno);
		Map<String,Object> jsonRs = doCommonRequest(encrypt, requestConent);
		return jsonRs;
	}

	public Map<String, Object> doConsumeBack(String posno, String winno,String flowcode) {

		boolean encrypt = false;
		String requestConent = RequestUtil.generateConsumeBackRequest(encrypt,posno,winno,flowcode);
		Map<String,Object> jsonRs = doCommonRequest(encrypt, requestConent);
		return jsonRs;
	}
	
	
	/**
	 * 纠错请求
	 * @param posno
	 * @param winno
	 * @param beginTime
	 * @param endTime
	 * @param page
	 * @return
	 */
	public Map<String, Object> jcPosFlow(String posno, String winno,String flowcode,String jymoney,String sjmoney) {

		boolean encrypt = false;
		String requestConent = RequestUtil.generatePosFlowJcRequest(encrypt, posno, winno,flowcode,jymoney,sjmoney);
		Map<String,Object> jsonRs = doCommonRequest(encrypt, requestConent);
		return jsonRs;
	}
	
	
	/**
	 * 公共发送请求
	 * @param posno
	 * @param possno
	 * @param winno
	 * @return
	 */
	public Map<String, Object> doCommonRequest(boolean encrypt ,String requestConent) {

		String result = null;
		List<String> serverList = serverUtils.getAllAviableServers();
		if(serverList==null || serverList.isEmpty()){
			//尝试依次服务器查询
			serverList = serverUtils.getAllServers();
			for(String name : serverList){
				result = Util.getResult(urlPrex.replace("${SERVER}", name),requestConent);
				if(result!=null){
					serverUtils.setServer(name, "1");
					break;
				}
			}
		}else{
			for(String server : serverList){
				result = Util.getResult(urlPrex.replace("${SERVER}", server),requestConent);
				if (result != null) {
					serverUtils.setServer(server, "1");
					break;
				}else{
					serverUtils.setServer(server, "0");
				}
			}
		}
		
		Map<String, Object> rsInfo = new HashMap<String, Object>();
		rsInfo.put("is_success", -1);
		if (result == null) {
			return rsInfo;
		}
		String rs = null;
		if (encrypt) {
			try {
				rs = new String(Base64.decode(result), "UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				return rsInfo;
			}
		} else {
			rs = result;
		}
		Map<String, Object> jsonRs = JSON.parseObject(rs, Map.class);
		if (jsonRs.get("return_code") != null && String.valueOf(jsonRs.get("return_code")).equalsIgnoreCase("1")) {
			jsonRs.put("is_success", 1);
		} else {
			
			
			if(jsonRs.get("code")!=null && String.valueOf(jsonRs.get("code")).equals("25")){
				//签名不对
				jsonRs.put("is_success", 0);
				jsonRs.put("error_code", "");
				jsonRs.put("error_msg", "输入了非法字符");
			}else{
				jsonRs.put("is_success", 0);
				jsonRs.put("error_code", String.valueOf(jsonRs.get("return_code")));
				jsonRs.put("error_msg", String.valueOf(jsonRs.get("return_msg")));
			}
			
			
		}
		return jsonRs;
	}
}
